/**
 * 
 */
package com.renmai.contact;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.renmai.R;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Contacts.People;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

/**
 * @author Issac
 *
 */
public class ViewContactListActivity extends ListActivity  {
	
	public static final int EDIT = Menu.FIRST;
	public static final int DELETE = Menu.FIRST + 1;
	public static final int EDIT_CONTACT_REQUEST_CODE = 0;
	public static final int EDIT_OK = 1;
	
	List<Map<String, Object>> contactList = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		contactList = getAllContacts();
		
		//触发长按式事件
		getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				
				Toast.makeText(ViewContactListActivity.this, "yeah", Toast.LENGTH_LONG).show(); 
				return false;
			}
			
		});
	        
		SimpleAdapter adapter = new SimpleAdapter(this, contactList, R.layout.listcontact,
				                new String[]{"name", "id"},
				                new int[] {R.id.list_contact_name, R.id.list_contact_id});
		setListAdapter(adapter);
		
		//注册菜单项
		registerForContextMenu(getListView());
	}

	
	
	//item单击事件
	@Override
	protected void onListItemClick(ListView listView, View v, int position, long id) {
		super.onListItemClick(listView, v, position, id);
		if (contactList.size() > 0){
			Log.i("logging..." ,(String)contactList.get(position).get("name"));
			Log.i("position..." ,position+"");
			Log.i("id..." ,contactList.get(position).get("id").toString());
		}
		
	}
	
	//弹出菜单选中事件
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch(item.getItemId()){  
        case EDIT: 
        	Intent intent = new Intent(ViewContactListActivity.this, EditContactActivity.class);
        	AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        	
        	Bundle b = new Bundle();
        	b.putInt("ids", new Integer(contactList.get(menuInfo.position).get("id").toString()).intValue());
        	intent.putExtras(b);
        	
			startActivityForResult(intent, EDIT_CONTACT_REQUEST_CODE);
			
			int version = Integer.valueOf(android.os.Build.VERSION.SDK);
			if(version  >= 5) {     
			     overridePendingTransition(R.layout.zoomin, R.layout.zoomout);  //此为自定义的动画效果，下面两个为系统的动画效果  
			     //overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);    
			     //overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);  
			}  
        	break;  
        case DELETE:
        	Log.i("item", "back");
        	break;  
		}  
		return super.onContextItemSelected(item);
	}


	//弹出菜单
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(0, EDIT, 0, R.string.edit_contact);  //添加两个菜单项
        menu.add(0, DELETE, 1, R.string.delete_contact);   
		super.onCreateContextMenu(menu, v, menuInfo);
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case EDIT_OK:
			Toast.makeText(ViewContactListActivity.this, "编辑成功", Toast.LENGTH_LONG).show(); 
			contactList = getAllContacts();
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}



	private List<Map<String, Object>> getAllContacts() {
		List<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;

		// 获取本机联系人
		Cursor cur = getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI,
				null,
				null,
				null,
				ContactsContract.Contacts.DISPLAY_NAME
						+ " COLLATE LOCALIZED ASC");
		if (cur.moveToFirst()) {
			do {
				//SamContact samContact = new SamContact();
				map = new HashMap<String, Object>();
				//samContact.isChoosed = false;
				int idColumn = cur
						.getColumnIndex(ContactsContract.Contacts._ID);
				int displayNameColumn = cur
						.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
				// 获得联系人的ID号
				String contactId = cur.getString(idColumn);
				// 获得联系人姓名
				String disPlayName = cur.getString(displayNameColumn);
				System.out.println(disPlayName + "---" + contactId);
				map.put("id", contactId);
				map.put("name", disPlayName);
				//samContact.name = disPlayName;
				// 查看该联系人有多少个电话号码。如果没有这返回值为0
				int phoneCount = cur
						.getInt(cur
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
				if (phoneCount < 1) {
					continue;
				}
				Cursor phones = getContentResolver().query(
						ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
						null,
						ContactsContract.CommonDataKinds.Phone.CONTACT_ID
								+ " = " + contactId, null, null);
				if (phones.moveToFirst()) {
					do {
						// 遍历所有的电话号码
						String phoneNumber = phones
								.getString(phones
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						int phoneType = phones
								.getInt(phones
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
						if (phoneType == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) {
							//samContact.phone = phoneNumber;
							map.put("phone", phoneNumber);
							arrayList.add(map);
							break;
						}
					} while (phones.moveToNext());

				}
				phones.close();
				
				
				String emailAddress = "";
				//得到邮箱
				Cursor emails = getContentResolver().query(
						ContactsContract.CommonDataKinds.Email.CONTENT_URI,
						null,
						ContactsContract.CommonDataKinds.Email.CONTACT_ID
								+ " = " + contactId, null, null);
				while (emails.moveToNext()) {
					emailAddress = emails
							.getString(emails
									.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
				}
				emails.close();
				
				map.put("mail", emailAddress);
				

			} while (cur.moveToNext());
		}
		cur.close();
		
		// 获取sim卡联系人
		Uri uri = Uri.parse("content://icc/adn");
		Cursor cur2 = getContentResolver().query(
				uri,
				null,
				null,
				null,
				ContactsContract.Contacts.DISPLAY_NAME
						+ " COLLATE LOCALIZED ASC");
		System.out.println("contact num from sim card = " + cur2.getCount());
		System.out.println("---------------");
		if (cur2.moveToFirst()) {
			do {
				try {
					//SamContact samContact = new SamContact();
					map = new HashMap<String, Object>();
					//samContact.isChoosed = false;
					int displayNameColumn = cur2.getColumnIndex(People.NAME);
					int phoneColumn = cur2.getColumnIndex(People.NUMBER);
					
					//samContact.name = cur2.getString(displayNameColumn);
					if (cur2.getString(displayNameColumn) == null) {
						continue;
					}
					map.put("name", cur2.getString(displayNameColumn));
					//samContact.phone = cur2.getString(phoneColumn);
					
					if (cur2.getString(phoneColumn) == null) {
						continue;
					}
					map.put("phone", cur2.getString(phoneColumn));
					arrayList.add(map);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} while (cur2.moveToNext());
		}
		cur2.close();

		return arrayList;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
}
